// 忘记密码页面
import React, { useState } from 'react';
import { Link, useRouter } from 'next/router';
import welcomeStyles from '../styles/welcomePage.module.css';
import {
  AutoComplete,
  Button,
  Cascader,
  Checkbox,
  Col,
  Form,
  Input,
  InputNumber,
  Row,
  Select,
  message,
} from 'antd';  
import axios from 'axios';
const { Option } = Select;

const formItemLayout = {
  labelCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 8,
    },
  },
  wrapperCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 16,
    },
  },
};
const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0,
    },
    sm: {
      span: 16,
      offset: 8,
    },
  },
};
const FindPassword = () => {
  const router = useRouter();

  const [error, setError] = useState('');
  const [username, setUsername] = useState('');
  const [validcode, setValidcode] = useState('');
  const [newpassword, setNewpassword] = useState('');
  const [repassword, setRepassword] = useState('');
  const [email, setEmail] = useState('');
  const [form] = Form.useForm();

  const onFinish = (values) => {
    console.log('Request Body:', values); // 打印请求体内容
    axios.post('/api/user/forget_password', values, )
      .then((response) => {
        console.log('Success:', response.data);
        message.success('修改成功');
        // 使用router.push来导航到/main页面
        router.push('/login'); 
      })
      .catch((error) => {
        console.log('Error:', error);
        // 登录失败时的处理
        if (error.response) {
          // 服务器返回了错误响应
          const errorMessage = error.response.data.msg || '修改失败';
          message.error(errorMessage);
        } else if (error.request) {
          // 请求已发出，但没有收到响应
          message.error('请求失败，请检查网络连接');
        } else {
          // 发送请求时出了问题
          message.error('请求失败，请检查后端服务是否可用');
        }
      });
  };
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };
    const sendMail = async () => {
      const usernameValue = form.getFieldValue('username');
    const emailValue = form.getFieldValue('email');
      try {
        // 发送请求到后端发送验证码邮件 API
        const response = await axios.post('/api/user/sendmail', {
          username: usernameValue,
          email: emailValue,
        });
        message.success('验证码已经发送，请注意查收');
      } catch (error) {
        if (error.response) {
          const { status, data } = error.response;
          if (status === 400) {
            message.error(data.msg || '验证码发送失败');
          } else {
            message.error('验证码发送失败，发生未知错误');
          }
        } else if (error.request) {
          message.error('验证码发送失败，服务器未响应');
        } else {
          message.error('验证码发送失败，请求失败');
        }
      }
    };

  const [autoCompleteResult, setAutoCompleteResult] = useState([]);
  const websiteOptions = autoCompleteResult.map((website) => ({
    label: website,
    value: website,
  }));
  return (
    <div className={welcomeStyles.backgroundContainer}>   {/* 注册页面背景 */}
    <Form
      {...formItemLayout}
      form={form}
      name="register"
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
      style={{
        maxWidth: 600,
      }}
      scrollToFirstError
    >
        <Form.Item
        name="username"
        label="Username"
        rules={[
          {
            type: 'string',
            message: 'The input is not valid username!',
          },
          {
            required: true,
            message: 'Please input your username!',
          },
        ]}
      >
        <Input />
      </Form.Item>

      <Form.Item
        name="email"
        label="E-mail"
        rules={[
          {
            type: 'email',
            message: 'The input is not valid E-mail!',
          },
          {
            required: true,
            message: 'Please input your E-mail!',
          },
        ]}
      >
        <Input />
      </Form.Item>

      <Form.Item label="Captcha" extra="Please input the captcha you got from your email.">
        <Row gutter={8}>
          <Col span={12}>
            <Form.Item
              name="validcode"
              noStyle
              rules={[
                {
                  required: true,
                  message: 'Please input the captcha you got!',
                },
              ]}
            >
              <Input />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Button onClick={sendMail}>Get captcha</Button>
          </Col>
        </Row>
      </Form.Item>

      <Form.Item
        name="newpassword"
        label="New Password"
        rules={[
          {
            required: true,
            message: 'Please input your new password!',
          },
        ]}
        hasFeedback
      >
        <Input.Password />
      </Form.Item>

      <Form.Item
        name="repassword"
        label="Confirm Password"
        dependencies={['newpassword']}
        hasFeedback
        rules={[
          {
            required: true,
            message: 'Please confirm your password!',
          },
          ({ getFieldValue }) => ({
            validator(_, value) {
              if (!value || getFieldValue('newpassword') === value) {
                return Promise.resolve();
              }
              return Promise.reject(new Error('The new password that you entered do not match!'));
            },
          }),
        ]}
      >
        <Input.Password />
      </Form.Item>
      

      <Form.Item {...tailFormItemLayout}>
        <Button type="primary" htmlType="submit">
          重置密码
        </Button>
      </Form.Item>
    </Form>
    </div>
  );
};
export default FindPassword;